package com.lr.server.demo2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

/*
 * 创建服务器并启动
 */
public class Server {
	
	private ServerSocket server;
	
	private boolean isRunning = true;
	
	public static void main(String[] args) {
		Server server = new Server();
		server.start();
		
	}
	
	public void start(){
		try {
			server = new ServerSocket(8888);
			isRunning = true;
			this.recieve();
		} catch (IOException e) {
			stop();
		}
	}
	
	public void start(int port){
		try {
			server = new ServerSocket(port);
			isRunning = true;
			this.recieve();
		} catch (IOException e) {
			stop();
		}
	}
	
	public void recieve(){
		
		try {
			while(isRunning){
			    Socket socket = server.accept();
			    new Thread(new Dispatcher(socket)).start();
			}
		} catch (IOException e) {
			stop();
		}
		
	}
	
	public void stop(){
		isRunning = false;
	}

}
